package com.airena.repository;

import com.airena.context.BaseContext;
import com.airena.service.IChatMessageService;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.time.Duration;
import java.util.List;

/**
 * 会话记忆持久化对象
 */
@Slf4j
@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {
    
    //注入RedisTemplate
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //    聊天记录持久化到mysql
    @Autowired
    private IChatMessageService chatMessageService;

    // 存储当前请求的用户ID和角色ID
    private Long currentUserId;
    private Long currentRoleId;
    
    /**
     * 设置当前请求的用户ID和角色ID
     * @param userId 用户ID
     * @param roleId 角色ID
     */
    public void setCurrentUserInfo(Long userId, Long roleId) {
        this.currentUserId = userId;
        this.currentRoleId = roleId;
    }

    /**
     * 获取会话消息
     * @param memoryId
     * @return
     */
    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String json = stringRedisTemplate.opsForValue().get(memoryId);
        //把json字符串转化成List<ChatMessage>
        List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(json);
        return list;
    }

    /**
     * 更新会话消息
     * @param memoryId
     * @param list
     */
    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        //1.把list转换成json数据
        String json = ChatMessageSerializer.messagesToJson(list);

        // 日志记录传入的参数值
        log.debug("保存聊天记录: userId={}, roleId={}, memoryId={}", currentUserId, currentRoleId, memoryId);

        //    聊天记录持久化到mysql
        // 传递获取到的用户ID和角色ID
        chatMessageService.saveMessages(
            memoryId.toString(), 
            json, 
            currentUserId, 
            currentRoleId
        );
        //2.把json数据存储到redis中  过期时间一天
        stringRedisTemplate.opsForValue().set(memoryId.toString(),json, Duration.ofDays(1));
    }

    /**
     * 删除会话消息
     * @param memoryId
     */
    @Override
    public void deleteMessages(Object memoryId) {
        stringRedisTemplate.delete(memoryId.toString());
    }
}